<template>
	<view class="layer">
		<view v-if="showMSG">
			<view class="topBox" v-if="!disabled">
				<image class="avatar" :src="userInfo.avatarUrl ? userInfo.avatarUrl : userAUrl"></image>
				<view class="formLable">
					<view style="display: flex;">
						<view class="lableItem">
							{{ namePass(userInfo.name) || '用户' }}
						</view>
						<view class="lableItem" style="flex: 1;">
							{{ phonePass(userInfo.phone) || '' }}
						</view>
					</view>
					<view class="lableItem">
						{{ idCardPass(userInfo.idCard) }}
					</view>
				</view>
				<!-- <view class="perfect" @click="updateInfo">
				完善信息
			</view> -->
			</view>
			<view class="topBox" v-else>
				<image class="avatar" :src="userAUrl"></image>
				<view class="formLable">
					<view style="display: flex;">
						<view class="lableItem">
							{{ namePass(pObj.FullName) || '' }}
						</view>
						<view class="lableItem" style="flex: 1;">
							{{ phonePass(pObj.ReceiptPhone) || '' }}
						</view>
					</view>
					<view class="lableItem">
						{{ idCardPass(pObj.IdCard) || '' }}
					</view>
				</view>
			</view>
			<view class="container">
				<view v-for="(item, index) in data" :key="index">
					<view class="info">
						<h3>内容信息</h3>
						<view v-for="(im, ix) in dataHeader" :key="ix">
							<view class="cell" v-if="im.dataIndex != 'nums'">
								<text>{{ im.title }}</text>
								<b>{{ resetValue(im, item) }}</b>
								<!-- <b>{{ item[im.dataIndex]==null?'':item[im.dataIndex] }}</b> -->
							</view>
						</view>
						<view class="cell"
							style="display: flex;justify-content: flex-end;text-align: right; border-top: 1px dashed #ccc">
							<span style="width: 100px;line-height: 2;">签收量</span>
							<input :disabled="disabled" v-model="item.nums" class="number" type="number"
								@input="different" placeholder="请输入签收量" />
						</view>
					</view>
				</view>
				<view class="info">
					<h3>签收照片</h3>
					<uni-file-picker file-mediatype="image" :del-icon="!disabled" v-model="fileList"
						:auto-upload="false" mode="grid" :sourceType="['camera']" :disabled="disabled" limit="5"
						@select="afterRead" @delete="handleDelete" />
				</view>
				<view class="info">
					<h3>签收视频</h3>
					<uni-file-picker file-mediatype="video" :del-icon="!disabled" :auto-upload="false" mode="grid"
						:sourceType="['camera']" :disabled="disabled" limit="1" @select="afterReadVideo"
						@delete="handleDeleteVideo" v-if="!videoSrc" />
					<video :src="videoSrc" v-else controls></video>
				</view>
				<view v-if="disabled" class="info">
					<button v-if="!newSign && SignList.length < SignNum" @click="handleSignature">再次签名</button>
				</view>
				<view class="info" style="border: none">
					<h3>签收人</h3>
					<view class="cell">
						<view v-if="Sign">
							<view :key="i" v-for="i in SignList" class="flexCell" @click="handleSignature">
								<!-- <img :src="Sign" alt="" class="imgSignature" /> -->
								<img :src="i" alt="" class="imgSignature" />
							</view>
						</view>
						<view v-else @click="handleSignature" style="
			              height: 200px;
			              border: 1px solid #ccc;
			              line-height: 200px;
			              text-align: center;
						  width: 100%;
			            ">
							请签名
						</view>
					</view>
					<view class="positionBox">
						<view class="positionLine">
							{{ pObj.SignInAddress ? pObj.SignInAddress : '请获取位置信息' }}
						</view>
						<button class="positionBtn" size="mini" type="primary" @click="getPosition"
							:disabled="disabled">
							<uni-icons color="#fff" type="location" size="30" class="positionIcon"></uni-icons>
						</button>
					</view>
				</view>
			</view>
			<view class="fixedBox">
				<!-- 已签收或拒收 -->
				<view v-if="disabled">
					<view style="display: flex; justify-content: space-between;">
						<button class="submitButton" disabled style="width: 270rpx;">{{ Status == 1 ? '已签收' : Status
							==
							2 ? '已拒收' : Status == 3 ? '部分签收' : '' }}</button>
						<button v-if="!newSign" class="submitButton" @click="toDownload" round type="primary">完成
						</button>
						<button v-else class="submitButton" round type="primary" @click="submitSign">提交签名</button>

					</view>
				</view>
				<!-- 签收或拒收 -->
				<view v-else
					style="display: flex; justify-content: space-between;align-items: flex-end;box-sizing: border-box;    padding: 0 10px;">
					<button
						:style="{ width: '48%', color: '#fff', 'background-color': difference != -1 ? '#e6a23c' : '#1aad19' }"
						class="submitButton" @click="handleGenerate(true)">
						{{ difference != -1 ? '提交差异' : '确认' }}
					</button>
					<button style="width: 48%" class="submitButton" type="warn" @click="handleGenerate(false)">拒收
					</button>
				</view>
			</view>
			<!-- 确认说明 -->
			<uni-popup ref="remark" type="center" :is-mask-click="false">
				<view class="remarkBox">
					<view class="title">
						请输入{{ title }}
					</view>
					<view class="content">
						<textarea class="textarea" :show-confirm-bar="false" :maxlength="1000" v-model="pObj.Memo"
							:placeholder="'请输入' + title">
					</textarea>
						<view class="memoLength">
							{{ memoLength }}/1000
						</view>
					</view>
					<view v-if="title != '拒收说明'">
						<view v-for="item in entity.evaluation" :key="item" class="content" style="display: flex;">
							<text style="margin-right: 30rpx;">{{ item }}</text>
							<uni-rate v-if="item == '服务'" v-model="entity['service']" />
							<uni-rate v-if="item == '物流'" v-model="entity['logistics']" />
							<uni-rate v-if="item == '产品'" v-model="entity['product']" />
						</view>
					</view>
					<view class="footer">
						<text @click="beforeClose">取消</text>
						<text class="confirmBtn" @click="dialogConfirm">确认</text>
					</view>
				</view>
			</uni-popup>
			<!-- 弹出签字 -->
			<uni-popup ref="popup" background-color="#fff" type="bottom" :is-mask-click="false">
				<Sign ref="sign" :showSign="true" @finish="signFinish" @close="signClose" />
			</uni-popup>
			<!-- 确认说明 -->
			<uni-popup ref="codeBox" type="center" :is-mask-click="false">
				<view class="remarkBox">
					<view class="title">
						请输入验证码
					</view>
					<view class="content">
						<view style="display: flex;">
							<input v-model="code"
								style="border-bottom: 1px solid #ccc;font-size: 20px;height: 28px;flex: 1;"
								type="number">
							<button size="mini" style="width: 70px;" :disabled="oneMinute < 60"
								@click="sendCodeSubmit">{{ oneMinute < 60 ? oneMinute + 'S' : '获取' }}</button>
						</view>
					</view>
					<view class="footer">
						<text @click="codeClose">取消</text>
						<text class="confirmBtn" @click="codeConfirm">确认</text>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	// import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
	import Sign from '@/components/sign.vue'
	import {
		idCardPass,
		namePass,
		phonePass
	} from '@/utils/PrivacyPass.js'
	// import {
	// 	CLIENT_RENEG_LIMIT
	// } from 'tls';
	var qqmapsdk;
	// const NumFormatting = function(data) {
	// 	if (data != null) {
	// 		return Number(data)
	// 			.toFixed(2)
	// 			.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,");
	// 	} else {
	// 		return "";
	// 	}
	// };
	export default {
		components: {
			Sign
		},
		computed: {
			memoLength() {
				return this.pObj.Memo ? this.pObj.Memo.length : 0
			},
			SignList() {
				console.log(this.Sign.split('%{}').filter(item => item != '' && item != 'null'), 'signlist')
				return this.Sign.split('%{}').filter(item => item != '' && item != 'null')
			}
		},
		data() {
			return {
				newSign: false,
				pObj: {},
				showMSG: true,
				entity: {},
				data: [],
				SignNum: 1,
				digit: "",
				lineWidth: 6,
				lineColor: "#000000",
				bgColor: "#fff",
				resultImg: "",
				isCrop: false,
				time: 10,
				timeShow: false,
				Interval: null,
				fileList: [],
				fileListVideo: [],
				showPopup: false,
				Sign: "",
				disabled: false, // 控制页面所有操作功能
				title: "",
				Status: "3",
				videoSrc: '',
				userAUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
				userInfo: {},
				userList: [], // 签收人
				timer: null, // 签收码定时器 
				oneMinute: 60, // 签收倒计时
				code: '', // 签收码
				dataHeader: [], // 表格头
				difference: -1,
				address: '',
				checkPhone: false,
				location: {}, // 收货坐标
				nowLocation: {}, // 当前坐标
				CustomerName: '',
				Company: '',
				showCodeBox: false
			}
		},
		onShow() {
			this.newSign = false;
			// this.SignNum=1;
			let obj = uni.getStorageSync('userInfo') || {}
			console.log(obj, '');
			if (!obj.phone) {
				uni.redirectTo({
					url: '/pages/authorization/authorization?isUser=1'
				})
				return
			}
			this.userInfo = typeof obj == 'object' ? obj : {},

				this.disabled = false;
			let id = uni.getStorageSync('Id')
			if (!id) {
				uni.redirectTo({
					url: '/pages/index/index'
				})
				uni.showToast({
					icon: 'none',
					title: '获取失败,请重新扫描二维码'
				})
				return;
			}
			this.$http('post', "/BO/BillList/GetBillData", {
				id
			}).then(async (res) => {
				if (res.Success) {
					console.log(res);
					// 签收手机号不符打回
					await this.checkCustomerPhone(res.Data)
					this.pObj = res.Data;
					if (!this.pObj.SignInAddress) this.pObj.SignInAddress = this.address
					if (res.Data.Status != 0) {
						this.Status = res.Data.Status
						this.disabled = true;
						if (res.Data.Sign) {
							this.Sign = res.Data.Sign;
							for (let i = 4; i > 0; i--) {
								this.Sign = res.Data["Sign" + i] + '%{}' + this.Sign;
							}
						}
						this.$http('post', '/Base/Base_Template/GetCompanyTemp?CompayId=' + res.Data
							.Company, {}).then(resjson => {
							this.SignNum = resjson.Data.SignNum;
						})
						uni.showToast({
							icon: 'none',
							title: '此货单已完成'
						})
					}
					// 是否需要从本地返填手机号
					if (!this.pObj.ReceiptPhone) this.pObj.ReceiptPhone = this.userInfo.phone
					// 货品图片
					if (res.Data.Imgs) {
						this.fileList = res.Data.Imgs.split(',').map(item => ({
							url: item
						}))
					}
					this.videoSrc = res.Data.Video;
					// 签收人图片
					if (res.Data.UserImage) {
						this.userList = [{
							url: res.Data.UserImage
						}]
					} else if (this.userInfo.avatarUrl) {
						this.userList = [{
							url: this.userInfo.avatarUrl
						}]
					}
					// 是否验证签收人手机号
					if (res.Data.IscheckPhone) this.checkPhone = res.Data.IscheckPhone
					if (res.Data.ContactPersonName) this.pObj.FullName = res.Data.ContactPersonName
					uni.setStorageSync("billId", res.Data.BillId)
					if (res.Data.Content) {
						this.entity = JSON.parse(res.Data.Content);
						console.log(this.entity);
						if (this.entity.printlist.length > 0) {
							let arr = []
							this.entity.printlist.filter((item) => {
								if (item.Keys == "table") {
									arr = [item]
								} else if (item.Keys == 'CustomerName') {
									this.CustomerName = item.value
								} else if (item.Keys == 'Company') {
									this.Company = item.value
								}
							});
							if (arr.length > 0) {
								if (this.data.length > 0) return
								this.dataHeader = arr[0].columns
								this.data = arr[0].datalist;
								this.data.forEach(im => im.nums = Number(im.Quantity))
							}
							// 收货坐标 有距离限制再请求
							if (uni.getStorageSync('LType')) {
								let address = this.entity.printlist.filter(item => item.Keys == 'Addres')
								console.log(address);
								if (address.length > 0) {
									this.getCoordinate(address[0].value)
								}
							}
							console.log(this.data, 329)
						} else {
							this.data = [];
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '暂无信息'
						})
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '数据获取失败!请刷新页面重试'
					})
				}
			});
		},
		onLoad() {
			uni.showLoading()
			qqmapsdk = new QQMapWX({
				key: 'CELBZ-7EU6U-4WPV4-BKP5Q-DU4G6-R4BEE'
			})
			let obj = uni.getStorageSync('userInfo') || {}
			if (obj.phone) {
				this.getPosition()
			}

			let id = uni.getStorageSync('Id')
			this.$http('post', '/Base_Manage/Base_Company/GetSignState?Id=' + id).then(res => {
				if (res.Success) this.showCodeBox = res.Data
			})
		},
		methods: {
			resetValue(val, itemdata) {
				console.log(itemdata[val.dataIndex], )
				console.log(val)
				if (itemdata[val.dataIndex]) {
					if (val.type === "text") {
						return itemdata[val.dataIndex];
					} else if (val.type === "number") {
						return this.NumFormatting(
							itemdata[val.dataIndex],
							Number(val.decimals ? val.decimals : 2)
						);
					} else {
						console.log(val)
						console.log(this.NumFormatting(itemdata[val.dataIndex], 2))
						return this.NumFormatting(itemdata[val.dataIndex], 2);
					}
				} else {
					return "";
				}
			},
			NumFormatting(data, num = 2) {

				if (isNaN(Number(data))) {
					return data;
				} else {
					return Number(data).toFixed(num);
				}
			},
			async checkCustomerPhone(e) {
				let obj = uni.getStorageSync('userInfo') || {}
				await this.$http('post', "/BO/CustomerInfo/CustomerSignValid", {
					CompanyId: e.Company,
					CustomerId: e.CustomerId,
					Name: obj.name,
					Phone: obj.phone,
					IdCard: obj.idCard,


				}).then(result => {
					console.log(result, '222');
					if (!result.Data) {
						this.showMSG = result.Data;
						uni.showModal({
							title: '提示',
							content: '当前手机号与签收人不符,请联系发货方',
							showCancel: false,
							success: (val) => {
								if (val.confirm) {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}
							}
						})
						return
					}
				})
			},
			// 获取收货地址坐标
			getCoordinate(address) {
				this.$http('post', '/BO/BillList/Getaddress?address=' + address).then(res => {
					if (JSON.parse(res.Data).Success) {
						let obj = JSON.parse(JSON.parse(res.Data).data)
						if (obj.status == 0) {
							this.location = obj.result.location
							console.log(this.location);
						}
					}
				})
			},
			// 隐私加密
			idCardPass(text) {
				return idCardPass(text)
			},
			namePass(text) {
				return namePass(text)
			},
			phonePass(text) {
				return phonePass(text)
			},
			// 差异计算
			different(e) {
				let num = 0;
				let allNum = 0;
				let idx = this.data.findIndex(item => item.nums != item.Quantity)
				this.difference = idx
			},
			// 完善信息
			updateInfo() {
				uni.navigateTo({
					url: '/pages/UpdateInfo/UpdateInfo'
				})
			},
			// 获取签收码
			async sendCodeSubmit() {
				let flag = null
				let BillId = uni.getStorageSync('Id')
				let url = ''
				if (this.checkPhone) url = '/BO/CustomerLinkman/GetSignCode'
				else url = '/BO/CustomerLinkman/GetSignCodeByMiniProgram'
				await this.$http('post', url + '?Phone=' + this.userInfo.phone + '&Id=' +
						BillId)
					.then((res) => {
						if (res.Success) {
							clearInterval(this.timer);
							this.timerDisabled = true;
							this.timer = setInterval(() => {
								this.oneMinute--;
								if (this.oneMinute <= 0) {
									clearInterval(this.timer);
									this.oneMinute = 60;
									this.timerDisabled = false;
								}
							}, 1000);
							uni.showToast({
								icon: 'none',
								title: '签收码发送成功'
							})
							flag = true
						} else {
							uni.showModal({
								title: '签收+',
								content: res.Msg,
								showCancel: false
							})
							flag = false
						}
					});
				return flag
			},
			// 位置信息
			getPosition() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						uni.hideLoading()
						this.nowLocation = {
							lat: res.latitude,
							lng: res.longitude
						}
						qqmapsdk.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (res) => {
								this.address = res.result.address
								this.pObj.SignInAddress = this.address
							},
							fail: (err) => {
								uni.showToast({
									icon: 'none',
									title: '位置信息获取失败,请打开定位重新尝试'
								})
							}
						})
					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '位置信息获取失败,请打开定位重新尝试'
						})
					}
				});
			},

			// 图片上传
			afterRead(file) {
				if (!file) return
				console.log(file);
				const fileArr = file.tempFiles.map(item => item.file.path)
				fileArr.forEach(item => {
					uni.compressImage({
						src: item,
						quality: 30,
						success: async result => {
							let res = await uni.uploadFile({
								url: this.$baseUrl +
									'/Base_Manage/Upload/UploadFileProductByForm',
								filePath: item,
								name: 'file'
							});
							if (res.length > 1) {
								let data = JSON.parse(res[1].data)
								this.fileList.push({
									url: data.thumbUrl
								})
							} else {
								uni.showToast({
									icon: 'none',
									title: '图片上传失败,请重试'
								})
								return false
							}
						}
					})
				})
			},
			//视频上传
			afterReadVideo(file) {
				if (!file) return
				console.log(file);
				this.fileListVideo = [];
				const fileArr = file.tempFiles.map(item => item.file.path)
				fileArr.forEach(item => {
					// uni.compressImage({
					// 	src: item,
					// 	quality: 30,
					// 	success: async result => {
					uni.uploadFile({
						url: this.$baseUrl +
							'/Base_Manage/Upload/UploadFileProductByForm',
						filePath: item,
						name: 'file'
					}).then(res => {
						console.log(res, '666')
						if (res.length > 1) {
							let data = JSON.parse(res[1].data)
							this.fileListVideo.push({
								url: data.thumbUrl
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '图片上传失败,请重试'
							})
							return false
						}
					});

					// 	}
					// })
				})
			},
			handleDelete(e) {
				let index = this.fileList.findIndex(item => item.url == e.tempFilePath)
				this.fileList.splice(index, 1)
			},
			handleDeleteVideo(e) {
				let index = this.fileListVideo.findIndex(item => item.url == e.tempFilePath)
				this.fileListVideo.splice(index, 1)
			},
			upload() {
				uni.chooseMedia({
					count: 9,
					mediaType: ['image', 'video'],
					sourceType: ['camera'],
					maxDuration: 10,
					camera: 'back',
					success: async (result) => {
						let res = await uni.uploadFile({
							url: this.$baseUrl + '/Base_Manage/Upload/Filleimag',
							filePath: result.tempFiles,
							name: 'file'
						});
						console.log(res);
						if (res.length > 1) {
							let data = JSON.parse(res[1].data)
							this.fileList.push({
								url: data.Data
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '上传失败,请重试'
							})
							return false
						}
					}
				})

			},
			toDownload() {
				uni.navigateTo({
					url: '/pages/Complete/Complete?Status=' + this.pObj.Status
				})
			},
			// 签字板
			handleSignature() {
				// if (this.disabled) return
				this.$refs.popup.open()
			},
			submitKeys(obj, key, value) {
				let i = 0;
				while (i < 5) {
					if (!obj[key + i]) {
						obj[key + i] = value
						break
					}
					i++;
				}
			},
			async submitSign() {
				this.pObj.Sign = this.SignList[0]; // 签名
				this.pObj.Sign1 = this.SignList[1]; // 签名
				this.pObj.Sign2 = this.SignList[2]; // 签名
				this.pObj.Sign3 = this.SignList[3]; // 签名
				this.pObj.Sign4 = this.SignList[4]; // 签名
				// this.submitKeys(this.pObj, 'FullName', this.userInfo.name)
				// this.submitKeys(this.pObj, 'ReceiptPhone', this.userInfo.phone)
				// this.submitKeys(this.pObj, 'IdCard', this.userInfo.idCard)
				// this.submitKeys(this.pObj, 'IP', uni.getStorageSync('DeviceId'))
				// this.submitKeys(this.pObj, 'DeviceName', uni.getStorageSync('DeviceName'))
				// console.log(this.pObj)
				await this.$http('post', "/BO/BillList/SaveSignData", this.pObj).then(async (res) => {
					if (res.Success) {
						uni.showToast({
							icon: 'none',
							title: '操作成功!'
						})
						// if (this.title == '确认说明' && this.pObj.IsEvidence) await this.toChain()
						uni.navigateTo({
							url: '/pages/Complete/Complete?Status=' + this.pObj.Status
						})
					} else {
						uni.showToast({
							icon: 'none',
							duration: 2000,
							title: res.Msg
						})
					}
					uni.hideLoading()
				});
				await this.$http('post', '/BO/BillList/GetOpenIdList?Id=' + this.pObj.Id).then(async res => {
					if (res.Success) {
						// token获取
						let result = await this.$http('GET', '/Base_Manage/Home/GetWxAccessTokenNoCode')
						let access_token = JSON.parse(result.Data).access_token
						res.Data.forEach(item => {
							this.publicPush(access_token, item)
						})
					}
				})
			},
			signFinish(src) {
				if (src == '1') this.Sign = this.userInfo.sign
				else if (this.newSign) {
					let arr = this.Sign.split('%{}').filter(item => item != '')
					arr[0] = src;
					this.Sign = arr.join('%{}');
				} else this.Sign = src + '%{}' + this.Sign;
				this.newSign = true;
				this.$refs.popup.close()
			},
			signClose() {
				this.$refs.popup.close()
			},
			// 签收或拒收
			async handleGenerate(bl) {
				this.pObj.Memo = "";
				if (this.data.length <= 0) return uni.showToast({
					icon: 'none',
					title: '请刷新页面重新获取数据'
				});
				// 距离判断
				let nowLocatonNum = uni.getStorageSync('LType')
				if (nowLocatonNum) {
					let locationNum = this.calculateDiscount(this.location.lng, this.location.lat, this.nowLocation
						.lng,
						this.nowLocation.lat)
					console.log(locationNum, nowLocatonNum, 626)
					if (locationNum > nowLocatonNum) return uni.showToast({
						icon: 'none',
						title: '当前位置距离指定签收位置过远,请到达指定位置进行签收'
					});
				}
				let idx = this.data.findIndex((item) => item.nums < 0);
				if (idx != -1) return uni.showToast({
					icon: 'none',
					title: '请检查签收数量'
				});
				// if (this.fileList.length <= 0) return uni.showToast({
				// 	icon: 'none',
				// 	title: '请拍摄签收照片'
				// })
				if (!this.Sign) return uni.showToast({
					icon: 'none',
					title: '请进行签字确认'
				});
				if (!this.pObj.SignInAddress) return uni.showToast({
					title: '请获取位置信息',
					icon: 'none'
				})
				this.bl = bl
				// 未输入验证码发送
				if (this.showCodeBox && !this.code) {
					this.$refs.codeBox.open()
				} else {
					this.showSubmit()
				}
			},
			// 验证码取消
			codeClose() {
				this.code = ''
				this.$refs.codeBox.close()
			},
			// 验证码确认
			async codeConfirm() {
				let resutl = await this.$http('post', '/BO/BillList/ValidateCode?Id=' + this.pObj.Id + '&SignCode=' +
					this.code)
				if (resutl.Success && resutl.Data) this.showSubmit()
				else uni.showToast({
					icon: 'none',
					title: '验证码错误'
				})
			},
			// 提交
			showSubmit() {
				this.$refs.codeBox.close()
				// 判断是否为点击拒收
				if (!this.bl) {
					this.title = "拒收说明";
					this.$refs.remark.open()
					this.pObj.Status = 2;
					return;
				}
				// 差值
				if (this.difference != -1) {
					this.title = "差异说明";
					this.$refs.remark.open()
					this.pObj.Status = 3;
					let arr = this.data.filter(item => (item.Quantity || 0) - (item.nums || 0) !=
						0)
					let str = arr.map(item => {
						console.log();
						return item.cInvName + ' 差异: ' + ((item.nums || 0) - (item
							.Quantity || 0))
					}).join('；\r\n')
					this.pObj.Memo = str
					return;
				}
				this.title = "确认说明";
				this.$refs.remark.open()
				this.pObj.Status = 1;
				this.pObj.UserImage = this.userList.length > 0 ? this.userList[0].url : ''
			},
			// 收货说明弹窗
			beforeClose() {
				this.$refs.remark.close()
			},
			dialogConfirm() {
				if (this.title != "确认说明" && this.pObj.Memo == "") {
					uni.showToast({
						icon: 'none',
						title: "请填写" + this.title
					})
					return false;
				}
				if (this.entity.evaluation && this.entity.evaluation.length > 0 && this.title != '拒收说明') {
					let flag = false
					this.entity.evaluation.forEach(item => {
						if (item == '服务' && !this.entity['service']) flag = true
						else if (item == '物流' && !this.entity['logistics']) flag = true
						else if (item == '产品' && !this.entity['product']) flag = true
					})
					if (flag) return uni.showToast({
						icon: 'none',
						title: '请进行星级评分'
					})
				}
				this.$refs.remark.close()
				this.submit();
			},
			// 保存
			async submit() {
				uni.showLoading()
				if (this.title == '拒收说明') this.data.forEach(item => item.nums = 0)
				this.pObj.Imgs = this.fileList.map((item) => item.url).join(",");
				this.pObj.Video = this.fileListVideo.map((item) => item.url).join(",");
				// 表格
				let idx = this.entity.printlist.findIndex((item) => item.Keys == "table");
				this.entity.printlist[idx].datalist = this.data;
				// 备注
				let idx2 = this.entity.printlist.findIndex((item) => item.Keys == "Memo");
				if (idx2 !== -1) this.entity.printlist[idx2].value = this.pObj.Memo
				// 签收地址
				let idx3 = this.entity.printlist.findIndex((item) => item.Keys == "SignInAddress");
				if (idx3 !== -1) this.entity.printlist[idx3].value = this.pObj.SignInAddress
				this.pObj.Sign = this.SignList[0]; // 签名
				// this.pObj.Sign1 = this.SignList[1]; // 签名
				// this.pObj.Sign2 = this.SignList[2]; // 签名
				// this.pObj.Sign3 = this.SignList[3]; // 签名
				// this.pObj.Sign4 = this.SignList[4]; // 签名
				// this.pObj.Sign5 = this.SignList[5]; // 签名
				// this.pObj.Sign6 = this.SignList[6]; // 签名
				// this.pObj.Sign7 = this.SignList[7]; // 签名
				// this.pObj.Sign8 = this.SignList[8]; // 签名
				// this.pObj.Sign9 = this.SignList[9]; // 签名
				this.pObj.FullName = this.userInfo.name // 签收人名称
				this.pObj.ReceiptPhone = this.userInfo.phone // 签收人手机号
				this.pObj.IdCard = this.userInfo.idCard // 签收人身份证号
				this.pObj.Content = JSON.stringify(this.entity); // JSON
				this.pObj.IP = uni.getStorageSync('DeviceId') // 设备id
				this.pObj.DeviceName = uni.getStorageSync('DeviceName') // 手机型号
				// uni.setStorageSync('Sign', this.Sign) // 签字 本地缓存
				await this.$http('post', "/BO/BillList/SaveSignData", this.pObj).then(async (res) => {
					if (res.Success) {
						uni.showToast({
							icon: 'none',
							title: '操作成功!'
						})
						// if (this.title == '确认说明' && this.pObj.IsEvidence) await this.toChain()
						uni.navigateTo({
							url: '/pages/Complete/Complete?Status=' + this.pObj.Status
						})
					} else {
						uni.showToast({
							icon: 'none',
							duration: 2000,
							title: res.Msg
						})
					}
					uni.hideLoading()
				});
				await this.$http('post', '/BO/BillList/GetOpenIdList?Id=' + this.pObj.Id).then(async res => {
					if (res.Success) {
						// token获取
						let result = await this.$http('GET', '/Base_Manage/Home/GetWxAccessTokenNoCode')
						let access_token = JSON.parse(result.Data).access_token
						res.Data.forEach(item => {
							this.publicPush(access_token, item)
						})
					}
				})
			},
			// 上链
			async toChain() {
				let result = await this.$chttp('GET', '/Chain/auth?id=' + this.userInfo.phone)
				console.log(result);
				if (result.Success) uni.setStorageSync('token', 'Bearer ' + result.Data)
				else return
				this.$chttp('POST', '/Chain', {
					"shipperId": this.pObj.Company,
					"billId": this.pObj.Id,
					"body": JSON.stringify(this.pObj),
					"name": '回执单号:' + this.pObj.BillId,
					description: `${this.userInfo.name} ${this.userInfo.phone}对回执单${this.pObj.BillId}签收了`,
					cCusName: this.pObj.Customer || ''
				}).then(res => {
					console.log(res);
				})
			},
			// 公众号推送
			async publicPush(access_token, id) {
				this.$http('POST', '/Base_Manage/Home/PutWxMessage', {
					"AccessToken": access_token,
					JsonStr: JSON.stringify({
						touser: id,
						template_id: 'N83E6yjj2O2PavcmDgR3POlCLZfo3jDd8CAWBzZyx1s',
						url: 'https://hzq.yoojet.com/#/SendSMSMobile?id=' + this.pObj.Id,
						data: {
							'thing2': {
								value: this.pObj.CompayName,
								"color": "#173177"
							},
							'thing3': {
								value: this.pObj.Customer,
								"color": "#173177"
							},
							'time4': {
								value: this.pObj.CreateTime.substring(0, 10),
								"color": "#173177"
							},
							'time5': {
								value: this.getNowDate(),
								"color": "#173177"
							},
							'thing6': {
								value: this.userInfo.name,
								"color": "#173177"
							}
						}
					})
				}).then(res => {
					console.log(res);
				})

				// uni.request({
				// 	url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' +
				// 		access_token,
				// 	method: 'POST',
				// 	data: {
				// 		touser: id,
				// 		template_id: 'N83E6yjj2O2PavcmDgR3POlCLZfo3jDd8CAWBzZyx1s',
				// 		url: 'https://hzq.yoojet.com/#/SendSMSMobile?id=' + this.pObj.Id,
				// 		data: {
				// 			'thing2': {
				// 				value: this.Company,
				// 				"color": "#173177"
				// 			},
				// 			'thing3': {
				// 				value: this.CustomerName,
				// 				"color": "#173177"
				// 			},
				// 			'time4': {
				// 				value: this.pObj.CreateTime.substring(0, 10),
				// 				"color": "#173177"
				// 			},
				// 			'time5': {
				// 				value: this.getNowDate(),
				// 				"color": "#173177"
				// 			},
				// 			'thing6': {
				// 				value: this.userInfo.name,
				// 				"color": "#173177"
				// 			}
				// 		}
				// 	}
				// }).then(res => {
				// 	console.log(res);
				// })
			},
			// 计算坐标距离
			calculateDiscount(lng1, lat1, lng2, lat2) {
				const radLat1 = (lat1 * Math.PI) / 180.0;
				const radLat2 = (lat2 * Math.PI) / 180.0;
				const a = radLat1 - radLat2;
				const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
				let s =
					2 *
					Math.asin(
						Math.sqrt(
							Math.pow(Math.sin(a / 2), 2) +
							Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
						)
					);
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				s = s * 1000;
				if (isNaN(s)) {
					return 0;
				}
				s = Math.floor((s / 1000) * 100) / 100;
				// 小于1000米直接返回
				return s.toFixed(2);
			},
			// 日期
			getNowDate() {
				var date = new Date();
				var sign2 = ":";
				var year = date.getFullYear() // 年
				var month = date.getMonth() + 1; // 月
				var day = date.getDate(); // 日
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (day >= 0 && day <= 9) {
					day = "0" + day;
				}
				return year + "-" + month + "-" + day
			}
		}
	}
</script>

<style scoped lang="scss">
	.positionBox {
		display: flex;
		align-items: center;
		margin-top: 20px;
		height: 40px;

		.positionLine {
			flex: 1;
			height: 100%;
			overflow-y: scroll;
			box-sizing: border-box;
			border-bottom: 1px solid #ccc;
		}

		.positionBtn {
			height: 100%;
			background: linear-gradient(to bottom, #5cccfe, #2799f9);
			border: none;

			.positionIcon {
				line-height: 40px;
				color: #fff;
			}
		}
	}

	.avatar {
		width: 70px;
		height: 70px;
	}

	.topBox {
		height: 72px;
		overflow: hidden;
		box-sizing: border-box;
		display: flex;
		position: relative;
		align-items: center;
	}

	.formLable {
		display: flex;
		flex-direction: column;
		padding: 0 20rpx;
		flex: 1;

		.lableItem {
			height: 35px;
			line-height: 35px;
			margin-right: 10px;
			color: #000;
		}
	}

	.fixedBox {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		background-color: #fff;
		padding-bottom: 30px;
		z-index: 9;
	}

	.remarkBox {
		width: 80vw;
		border-radius: 10px;
		background-color: #fff;
		box-sizing: border-box;

		.title {
			text-align: center;
			line-height: 4;
			color: #666;
		}

		.content {
			padding: 10px;
			padding-top: 0;

			.textarea {
				border: 1px solid #b7b7b7;
				width: 100%;
				border-radius: 3px;
				padding: 5px;
				box-sizing: border-box;
			}

			.memoLength {
				text-align: right;
				color: #666;
			}
		}

		.footer {
			display: flex;
			border-top: 1px solid #f0f0f0;

			text {
				line-height: 3;
				text-align: center;
				flex: 1;
			}

			.confirmBtn {
				color: #007aff;
				border-left: 1px solid #f0f0f0;
			}
		}
	}

	.container {
		box-sizing: border-box;
		padding: 0 10px;
		box-shadow: 0 2px 10px #ccc;
		border-radius: 20px;
		width: 94%;
		margin: 0 auto;
		background: #fff;
	}

	.logoTitlelit {
		margin: 0;
		margin-bottom: 6vh;
		text-align: center;
		color: #fff;
		font-size: 20px;
		font-weight: bold;
	}

	.flexCell {
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
		height: 180px;
		overflow: hidden;
		width: 100%;
	}

	.imgSignature {
		transform: rotate(-90deg);
		width: 160px;
	}

	b {
		font-weight: normal;
		color: #777;
	}

	.layer {
		padding: 20px 10px;
		min-height: calc(100vh - 44px);
		padding-bottom: 90px;
		box-sizing: border-box;
	}

	h3 {
		margin: 0px 0;
	}

	.info {
		padding: 5px;
		line-height: 1.4;
		/* background: #fff; */
		margin: 10px 0;
		border-bottom: 1px solid #ccc;
		font-size: 12px;
	}

	.info .cell {
		color: #000;
		display: flex;

		text {
			min-width: 61px;
		}

		b {
			margin-left: 10px;
		}
	}

	.info .number {
		margin-left: 5px;
		border-radius: none;
		width: 120px;
		border: none;
		border-bottom: 1px solid #666;
		height: 22px;
		text-align: left;
	}

	.logo {
		width: 100%;
		height: 10vh;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}

	.logo img {
		width: 50px;
	}

	.logo .logoTitle {
		color: #fff;
		margin: 0;
		margin-bottom: 10px;
		font-weight: bold;
		font-size: 32px;
	}

	.van-button-css {
		border-radius: 10px;
		height: 36px;
		line-height: 36px;
	}

	.submitButton {
		margin: 0 auto;
		margin-top: 10px;
		width: 90vw;
		display: block;
		border-radius: 5px;
	}
</style>